#!/bin/bash

set -e
set -o pipefail

if [ -z ${CIRCLECI+x} ]; then
    echo "Not on Circle; refusing to run."
    exit 1
fi

branch="$CIRCLE_BRANCH"
if [ ! -z "$CIRCLE_TAG" ]; then
    branch='develop'
fi

if ! [[ "$branch" == "master" || "$branch" == "develop" || "$branch" == "next" || "$branch" == release/* ]]; then
    echo "Not on master, develop, next, release/* or a tag - not publishing."
    exit 1
fi

echo "//registry.npmjs.org/:_authToken=${NPM_AUTH_TOKEN}" > .npmrc
chmod 0600 .npmrc

if [[ "$branch" == "next" ]]; then
    echo "Publishing with next tag because branch name is next"
    # must set public access for scoped packages
    npm publish --tag next
else
    npm publish
fi
